import { depTree } from '@/api/sys/dep'
import { getMenuTree } from '@/api/sys/menu'
import { getDict } from '@/api/sys/dict'
import { getRoleOption } from '@/api/sys/role'

const state = {
  // 部门树
  depData: [],
  getDepFlag: false,
  // 菜单树
  menuData: [],
  getMenuFlag: false,
  dictData: {},
  // 角色下拉
  roleOptions: [],
  getRoleFlag: false,
  tableDict: {}
}

const mutations = {
  SET_DEPTREE: (state, data) => {
    state.depData = data
    state.getDepFlag = true
  },
  SET_MENUTREE: (state, data) => {
    state.menuData = data
    state.getMenuFlag = true
  },
  SET_DICTDATA: (state, obj) => {
    const { key, data } = obj
    state.dictData[key] = data
  },
  SET_ROLEDATA: (state, obj) => {
    state.roleOptions = obj
    state.getRoleFlag = true
  },
  SET_TABLE_DATA: (state, dictDatas) => {
    Object.keys(dictDatas).forEach((key) => {
      state.tableDict[key] = dictDatas[key]
    })
  }
}

const actions = {
  getDepTree({ commit, state }) {
    if (!state.getDepFlag) {
      depTree().then((res) => {
        const depData = [{ id: 0, label: '总集团', children: [...res.obj] }]
        commit('SET_DEPTREE', depData)
      })
    }
  },
  getMenuTree({ commit, state }) {
    if (!state.getMenuFlag) {
      getMenuTree().then((res) => {
        const parentMenuList = [{ id: 0, label: '主菜单', children: [...res.obj] }]
        commit('SET_MENUTREE', parentMenuList)
      })
    }
  },
  // 作废
  getDictData({ commit, state }, key) {
    if (!state.dictData[key]) {
      getDict(key).then((res) => {
        const data = res.obj
        commit('SET_DICTDATA', { key, data })
      })
    }
  },
  getRoleData({ commit, state }) {
    if (!state.getRoleFlag) {
      getRoleOption().then((res) => {
        commit('SET_ROLEDATA', res.obj)
      })
    }
  }
}

const getters = {
  dictDatas: state => keys => {
    return state.dictData[keys]
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
